package app.controller.excel;

import app.controller.excel.entity.GDCL;
import app.entity.UserSession;
import app.utils.BasePathCollector;
import app.utils.Common;
import app.utils.DBDataGetterJDBCSiotwx;
import app.utils.DataResponse;
import com.zhou.ExcelExportor;
import ele.mapper.EleCycleReportMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import siotwx.dao.*;
import siotwx.entity.*;
import water.mapper.WaterCycleReportMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Controller
public class ExcelFiles {
	
	@Autowired
	@Qualifier("Warn_djDao")
	private Warn_djDao warn_djDao;
	
	@Autowired
	@Qualifier("Warn_jfDao")
	private Warn_jfDao warn_jfDao;
	
	@Autowired
	@Qualifier("Warn_jgDao")
	private Warn_jgDao warn_jgDao;
	
	@Autowired
	@Qualifier("Warn_tddDao")
	private Warn_tddDao warn_tddDao;
	
	@Autowired
	@Qualifier("Unlock_jfDao")
	private Unlock_jfDao unlock_jfDao;
	
	@Autowired
	@Qualifier("Unlock_jgDao")
	private Unlock_jgDao unlock_jgDao;

	@Autowired
	private EleCycleReportMapper eleCycleReportMapper;

	@Autowired
	private WaterCycleReportMapper waterCycleReportMapper;
	
	private final String warning_dj="warning_dj";
	private final String warning_jf="warning_jf";
	private final String warning_jg="warning_jg";
	private final String warning_tdd="warning_tdd";
	private final String meter_dl="meter_dl";
	private final String unlock_jf="unlock_jf";
	private final String unlock_jg="unlock_jg";
	private final String unlock_ggjl="unlock_ggjl";
	private final String water_data="water_data";
	private final String ele_data="ele_data";
	private String flagQ="";
	private long startTime=0L;
	@RequestMapping("/excel/file/{flag}")
	public void handler(@PathVariable("flag") String flag,HttpSession session, HttpServletRequest request,HttpServletResponse response) throws Exception{
		if (flag==null||"".equals(flag)||flag.length()<=0) {
			return ;
		}
		UserSession user = (UserSession) session.getAttribute(Common.sessionUser);
		flag=flag.replace(" ", "");
		if (flag.endsWith(",")) {
			flagQ=flag.substring(0, flag.length()-1);
		}else {
			String[] split = flag.split(",");
			flagQ=split[0];
			DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
			Date parse = format.parse(split[1]);
			startTime=parse.getTime();
		}
		switch (flagQ) {
		case warning_dj:
			warning_dj(response,startTime,user);
			break;
			
		case warning_jf:
			warning_jf(response,startTime,user);
			break;
			
		case warning_jg:
			warning_jg(response,startTime,user);
			break;
			
		case warning_tdd:
			warning_tdd(response,startTime,user);
			break;
			
		case meter_dl:
			meter_dl(response,request ,startTime,user);
			break;
			
		case unlock_jf:
			unlock_jf(response,startTime,user);
			break;
			
		case unlock_jg:
			unlock_jg(response,startTime,user);
			break;
			
		case unlock_ggjl:
			unlock_ggjl(response,startTime,user);
			break;

		default:
			break;
		}
		
		return;
	}


	@GetMapping("/excel/exportdata/{startTime}/{endTime}/{modId}")
	public void exportData(@PathVariable("startTime") Integer startTime,@PathVariable("endTime") Integer endTime,@PathVariable("modId") Integer modId
						  ,HttpSession session, HttpServletRequest request,HttpServletResponse response) throws Exception {
		UserSession user = (UserSession) session.getAttribute(Common.sessionUser);

		List<ReadData> read=null;
		StringBuffer name=new StringBuffer();
		name.append(startTime+"-"+endTime+"-");
						if(modId==3){
							read=getWaterData(endTime,startTime,user);
							name.append("Water");
						}else if(modId==4){
							read=getEleData(endTime,startTime,user);
							name.append("Ele");
						}else{
							read=getWaterData(endTime,startTime,user);
							List<ReadData> tmp=getEleData(endTime,startTime,user);
							for(ReadData r:tmp){
								read.add(r);
							}
							name.append("EleAndWater");
						}
						sortRead(read);
						for(int i=0;i<read.size();i++){
							read.get(i).setStartTime(startTime);
							read.get(i).setEndTime(endTime);
						}
		InputStream excel = new ExcelExportor().getExcel(read);
		DataResponse.StreamResponse(response, excel, name+".xls");
	}
	public void sortRead(List<ReadData> read){
		ReadData tmp=new ReadData();
		for(int i=0;i<read.size()-1;i++){

			for(int j=i+1;j<read.size();j++){
				int[] numI=sortNum(read.get(i).getDescription());
				int[] numJ=sortNum(read.get(j).getDescription());
				if((numI.length==2&&numJ.length==2)&&(numI[0]>numJ[0] || (numI[0]==numJ[0]&&numI[1]>numJ[1]))){
					tmp.setCha(read.get(i).getCha());
					tmp.setAddr_id(read.get(i).getAddr_id());
					tmp.setDescription(read.get(i).getDescription());
					tmp.setNameandphone(read.get(i).getNameandphone());
					tmp.setType(read.get(i).getType());
					read.get(i).setCha(read.get(j).getCha());
					read.get(i).setAddr_id(read.get(j).getAddr_id());
					read.get(i).setDescription(read.get(j).getDescription());
					read.get(i).setNameandphone(read.get(j).getNameandphone());
					read.get(i).setType(read.get(j).getType());
					read.get(j).setCha(tmp.getCha());
					read.get(j).setAddr_id(tmp.getAddr_id());
					read.get(j).setDescription(tmp.getDescription());
					read.get(j).setNameandphone(tmp.getNameandphone());
					read.get(j).setType(tmp.getType());
				}
			}
		}
	}
	 public int[] sortNum(String u){
		 Pattern p = Pattern.compile("\\d{1,}");
		 Matcher m = p.matcher(u);
		int [] num=new int[2];
		int i=0;
		 while (m.find()) {
			num[i++]=Integer.parseInt(m.group());
		 }
		return num;
	 }





	public List<ReadData> getWaterData(Integer endTime,Integer startTime,UserSession user) throws IllegalArgumentException, IllegalAccessException, IOException{
		DecimalFormat df   = new DecimalFormat("######0.00");
		List<ReadData> read = waterCycleReportMapper.getRead(startTime, endTime, user.getRegionId());
		for(ReadData rd:read){
			rd.setCha(Double.parseDouble(df.format(rd.getCha())));
		}

		return read;

	}
	public List<ReadData> getEleData(Integer endTime,Integer startTime,UserSession user) throws IllegalArgumentException, IllegalAccessException, IOException{
		DecimalFormat    df   = new DecimalFormat("######0.00");
		List<ReadData> read = eleCycleReportMapper.getRead(startTime, endTime, user.getRegionId());
		for(ReadData rd:read){
			rd.setCha(Double.parseDouble(df.format(rd.getCha())));
		}
		return read;

	}


	public void warning_dj(HttpServletResponse response,long time,UserSession user) throws IllegalArgumentException, IllegalAccessException, IOException{
		Map<String, Object> params=new HashMap<>();
		params.put(Warn_dj.FieldName.facRegionId.toString(), user.getRegionId());
		params.put(Warn_dj.FieldName.eventStart.toString(), time);
		List<Warn_dj> Warn_djList = warn_djDao.getlist(params);
		InputStream excel = new ExcelExportor().getExcel(Warn_djList);
		DataResponse.StreamResponse(response, excel, "warning_dj"+new SimpleDateFormat("yyyy_MM_dd:HH:mm:ss").format(new Date())+".xls");
		
	}
	public void warning_jf(HttpServletResponse response,long time,UserSession user) throws IllegalArgumentException, IllegalAccessException, IOException{
		Map<String, Object> params=new HashMap<>();
		params.put(Warn_jf.FieldName.facRegionId.toString(), user.getRegionId());
		params.put(Warn_jf.FieldName.eventStart.toString(), time);
		List<Warn_jf> warn_jfList = warn_jfDao.getlist(params);
		InputStream excel = new ExcelExportor().getExcel(warn_jfList);
		DataResponse.StreamResponse(response, excel, "warning_jf"+new SimpleDateFormat("yyyy_MM_dd:HH:mm:ss").format(new Date())+".xls");
	}
	public void warning_jg(HttpServletResponse response,long time,UserSession user) throws IllegalArgumentException, IllegalAccessException, IOException{
		Map<String, Object> params=new HashMap<>();
		params.put(Warn_jg.FieldName.facRegionId.toString(), user.getRegionId());
		params.put(Warn_jg.FieldName.eventStart.toString(), time);
		List<Warn_jg> warn_jgList = warn_jgDao.getlist(params);
		InputStream excel = new ExcelExportor().getExcel(warn_jgList);
		DataResponse.StreamResponse(response, excel, "warning_jg"+new SimpleDateFormat("yyyy_MM_dd:HH:mm:ss").format(new Date())+".xls");
	}
	public void warning_tdd(HttpServletResponse response,long time,UserSession user) throws IllegalArgumentException, IllegalAccessException, IOException{
		Map<String, Object> params=new HashMap<>();
		params.put(Warn_tdd.FieldName.facRegionId.toString(), user.getRegionId());
		params.put(Warn_tdd.FieldName.eventStart.toString(), time);
		List<Warn_tdd> warn_tddList = warn_tddDao.getlist(params);
		InputStream excel = new ExcelExportor().getExcel(warn_tddList);
		DataResponse.StreamResponse(response, excel, "warn_tdd"+new SimpleDateFormat("yyyy_MM_dd:HH:mm:ss").format(new Date())+".xls");
	}
	public void meter_dl(HttpServletResponse response,HttpServletRequest request,long time,UserSession user) throws IOException{
		response.sendRedirect(BasePathCollector.getBasePathWithoutPort(request)+"meter/excel/lastmonth");
	}
	public void unlock_jf(HttpServletResponse response,long time,UserSession user) throws Exception{
		Map<String, Object> params=new HashMap<>();
		params.put(Unlock_jf.FieldName.regionId.toString(), user.getRegionId());
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		params.put(Unlock_jf.FieldName.eventDate.toString(), simpleDateFormat.format(new Date(time)));
		List<Unlock_jf> unlock_jfList = unlock_jfDao.getlist(params);
		InputStream excel = new ExcelExportor().getExcel(unlock_jfList);
		DataResponse.StreamResponse(response, excel, "unlock_jf"+new SimpleDateFormat("yyyy_MM_dd:HH:mm:ss").format(new Date())+".xls");
	}
	public void unlock_jg(HttpServletResponse response,long time,UserSession user) throws Exception{
		Map<String, Object> params=new HashMap<>();
		params.put(Unlock_jg.FieldName.regionId.toString(), user.getRegionId());
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
		params.put(Unlock_jg.FieldName.eventDate.toString(), simpleDateFormat.format(new Date(time)));
		List<Unlock_jg> unlock_jgList = unlock_jgDao.getlist(params);
		InputStream excel = new ExcelExportor().getExcel(unlock_jgList);
		DataResponse.StreamResponse(response, excel, "unlock_jg"+new SimpleDateFormat("yyyy_MM_dd:HH:mm:ss").format(new Date())+".xls");
	}
	public void unlock_ggjl(HttpServletResponse response,Long time,UserSession user) throws Exception{
		String sql="SELECT * FROM workOrderProcess where regionId="+user.getRegionId();
		if (time!=null &&time>0) {
			sql+=" and startTime>="+time;
		}
		List<HashMap<String,String>> executeResult = DBDataGetterJDBCSiotwx.executeSqlWithResult(sql);
		//构建excel返回结果集
		List<GDCL> gdcls=new ArrayList<>();
		SimpleDateFormat format=new SimpleDateFormat("yyyy_MM_dd_HH:mm:S");
		String fileName="recovery_"+format.format(new Date())+".xls";
		if(executeResult!=null&&executeResult.size()>0){
			String res="",tel="",manamger="",over="",happen="",devCode="",desc="";
			for(Map<String, String> key:executeResult){
				res=key.get("result");
				if ("1".equals(res)) {
					res="已恢复";
				}else if ("0".equals(res)) {
					res="未处理";
				}
				tel=key.get("phoneNumber");
				manamger=key.get("realName");
				over=key.get("endTime");
				if (over.length()>4) {
					over=format.format(new Date(Long.valueOf(over)));
				}else {
					over="---";
				}
				happen=key.get("startTime");
				if (happen.length()>4) {
					happen=format.format(new Date(Long.valueOf(happen)));
				}
				devCode=key.get("code");
				desc=key.get("description");
				GDCL gdcl= new GDCL(desc,
									devCode,
									happen,
									over,
									manamger,
									tel, 
									res);
				gdcls.add(gdcl);
			}
			InputStream excel = new ExcelExportor().getExcel(gdcls);
			DataResponse.StreamResponse(response, excel, fileName);
			return ;
		}else {
			gdcls.add(new GDCL());
			InputStream excel = new ExcelExportor().getExcel(gdcls);
			DataResponse.StreamResponse(response, excel, fileName);
		}
		
	}
}
